<template>
    <div>
        <el-card>
            <!-- 添加按钮：调用openAddDialog，传null表示一级分类 -->
            <div style="margin-bottom: 16px;">
                <el-button type="primary" @click="handleAddProduct">
                    <el-icon>
                        <Plus />
                    </el-icon>商品上架
                </el-button>
            </div>

            <!-- 分类表格：树形结构 -->
            <el-form :inline="true" :model="searchForm" style="margin-bottom: 16px">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.title" @change="handleSearch" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-cascader v-model="searchForm.categoryIds" :options="categories" :props="{
                        checkStrictly: false,
                        value: 'id',
                        label: 'name',
                        children: 'children',
                        emitPath: true,
                        changeOnSelect: false
                    }" clearable placeholder="请选择商品分类"></el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch"><el-icon>
                            <Search />
                        </el-icon>查询</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tableData" border v-loading="loading" style="width: 100%;">
                <el-table-column prop="id" label="编号" width="100" align="center"></el-table-column>
                <el-table-column prop="title" label="商品名称"></el-table-column>
                <el-table-column prop="main_image" label="商品图片" width="100" align="center">
                    <template #default="scope">
                        <el-image :src="scope.row.main_image" v-if="scope.row.main_image"
                            style="width: 60px; height: 60px;"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="商品价格" width="100" align="center">
                    <template #default="scope">
                        ￥{{ scope.row.price }}
                    </template>
                </el-table-column>
                <el-table-column prop="stock" label="商品库存" width="100" align="center"></el-table-column>
                <el-table-column prop="sales" label="商品销量" width="100" align="center"></el-table-column>
                <el-table-column prop="status" label="商品状态" width="100" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
                        <el-tag v-else type="info">下架</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="商品描述" min-width="200">
                    <template #default="scope">
                        <el-tooltip class="item" effect="dark"
                            :content="scope.row.description ? scope.row.description.replace(/<[^>]*>/g, '') : ''"
                            placement="top">
                            <span>{{ scope.row.description ? scope.row.description.replace(/<[^>]*>/g, '') : ''
                            }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" @click="handleStatusChange(scope.row)"
                            :type="scope.row.status === 1 ? 'danger' : 'success'">{{
                                scope.row.status
                                    === 1 ? '下架' : '上架' }}</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
                :total="total" @current-change="handlePageChange" @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper" style="margin-top: 16px;"></el-pagination>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { getProductList, deleteProduct, updateProductStatus } from '../../api/product'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryTree } from '@/api/category'
import { useRouter } from 'vue-router'

const router = useRouter()

let loading = ref(false)
let searchForm = reactive({
    title: '',
    categoryIds: []
})

let categories = reactive([]) // 分类树形结构
let tableData = ref([]) // 商品列表数据
let currentPage = ref(1) // 当前页码
let pageSize = ref(10) // 每页显示的记录数
let total = ref(0) // 总记录数


const fetchProductList = async () => {
    loading.value = true
    try {
        const params = {
            title: searchForm.title,
            categoryId: (searchForm.categoryIds ?? []).length > 0
                ? (searchForm.categoryIds ?? [])[searchForm.categoryIds.length - 1]
                : '',
            pageNo: currentPage.value,
            pageSize: pageSize.value
        }
        console.log('请求参数:', params) // 添加这行来检查请求参数

        const res = await getProductList(params)
        console.log('商品列表接口返回', res);
        console.log('总数:', res.data.totalCount) // 检查总数是否正确

        if (res.code === 0) {
            tableData.value = res.data.data
            total.value = res.data.totalCount
        } else {
            ElMessage.error(res.msg)
        }
    } catch (error) {
        ElMessage.error("获取商品列表失败")
        console.error('请求错误', error);
    } finally {
        loading.value = false
    }
}

const fetchCategoryList = async () => {
    try {
        const res = await getCategoryTree()
        console.log("catgryRes", res);

        if (res.code === 0) {
            function cleanCategryChildren(list: any[]) {
                if (!Array.isArray(list)) return
                list.forEach(node => {
                    if (Array.isArray(node.children)) {
                        if (node.children.length === 0) {
                            delete node.children
                        } else {
                            cleanCategryChildren(node.children)
                        }
                    }
                })
            }
            cleanCategryChildren(res.data)
            categories.splice(0)
            categories.push(...res.data)
        }
    } catch (error) {
        ElMessage.error("获取分类列表失败")
    }
}

const handleSearch = () => {
    currentPage.value = 1
    fetchProductList()
}
const handleSizeChange = (size: number) => {
    pageSize.value = size
    fetchProductList()
    currentPage.value = 1
}

const handlePageChange = (page: number) => {
    currentPage.value = page
    fetchProductList()
}


const handleEdit = (row: any) => {
    router.push(`/main/productEdit/${row.id}`)
}

const handleAddProduct = () => {
    router.push('/main/productEdit')
}

const handleDelete = async (row: any) => {
    try {
        // 先弹出确认框
        await ElMessageBox.confirm(
            `确认要删除该商品吗？`,
            '提示',
            {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        );

        // 用户确认后再调用删除API
        const res = await deleteProduct(row.id)
        console.log('删除商品接口返回', res);
        if (res.code === 0) {
            ElMessage.success("删除成功")
            fetchProductList()
        } else {
            ElMessage.error(res.msg)
        }
    } catch (error) {
        // 用户取消操作或API调用失败
        if (error === 'cancel') {
            ElMessage.info('已取消删除');
        } else {
            ElMessage.error("删除商品失败")
        }
    }
}

const handleStatusChange = async (row: any) => {
    try {
        // 先弹出确认框
        await ElMessageBox.confirm(
            `确认要${row.status === 1 ? '下架' : '上架'}该商品吗？`,
            '提示',
            {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        );

        // 用户确认后再调用API
        const res = await updateProductStatus(row.id, row.status === 1 ? 0 : 1);
        console.log('更新商品状态接口返回', res);
        if (res.code === 0) {
            ElMessage.success(`${row.status === 1 ? '下架' : '上架'}成功`);
            fetchProductList();
        } else {
            ElMessage.error(res.msg);
        }
    } catch (error) {
        // 用户取消操作或API调用失败
        if (error === 'cancel') {
            ElMessage.info('已取消');
        } else {
            ElMessage.error("更新商品状态失败");
        }
    }
}

onMounted(() => {
    fetchProductList()
    fetchCategoryList()
})

</script>

<style scoped>
.ellipsis-text {
    display: block;
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>